import qs from 'qs'
import * as auth from '../authProvider'
import { useAuth } from '../context/authContext'

const apiUrl = process.env.REACT_APP_API_URL

interface Config extends RequestInit {
	data?: object
	token?: string
}

export const http = async (
	endpoint: string,
	{ data, token, headers, ...customConfig }: Config = {}
) => {
	const config = {
		method: 'GET',
		headers: {
			Authorization: token ? `Bearer ${token}` : '',
			'Content-Type': data ? 'application/json' : ''
		},
		...customConfig
	}
	// fetch api 中, get请求的参数要传到url中
	// 整理其余ajax请求参数
	if (config.method.toUpperCase() === 'GET') {
		endpoint += `?${qs.stringify(data)}`
	} else {
		config.body = JSON.stringify(data || {})
	}
	return window
		.fetch(`${apiUrl}/${endpoint}`, config)
		.then(async (response) => {
			// 无权限则登出
			if (response.status === 401) {
				await auth.logout()
				window.location.reload()
				return Promise.reject({ message: '请重新登录' })
			}
			// 获取登录数据
			const data = await response.json()
			if (response.ok) {
				return data
			} else {
				return Promise.reject(data)
			}
		})
}

export const useHttp = () => {
	const { user } = useAuth()
	// ts 操作符 utility types
	return (...[endpoint, config]: Parameters<typeof http>) =>
		http(endpoint, { ...config, token: user?.token })
}
